//获取dom元素的引用
const messageInput = document.getElementById("message-input");
const sendButton = document.getElementById("send-button");
const chatMessages = document.getElementById("chat-message");

let imList = document.querySelectorAll(".im-list")[0]

let jsAvatar;
let jrAvatar;

let params = new URLSearchParams(window.location.search);
const searchInput = document.getElementById('searchInput');
// const searchButton = document.getElementById('searchButton');
const searchResults = document.getElementById('searchResults');


let jrid = 1;
$.ajax({
    headers: {
        "id": localStorage.getItem("id"),
        "token": localStorage.getItem("token")
    },
    type: 'get',
    url: `/dev/searchMessage/reName/${jrid},`,
    async: false,
    success: function (result) {
        $("#jrName").text(result.data.jrName)
        $("#companyName").text(result.data.companyName)
    }

})


// 获取所有聊天列表项
const chatItems = document.querySelectorAll('.hr-list li');
// 获取所有聊天窗口容器
const chatWindows = document.querySelectorAll('.chat-message');


function chitchat(jrId) {


    let jrLi = document.getElementById(`bname${jrId}`)
    console.log(jrLi)
    for (let i = 0; i < jrLi.parentNode.children.length; i++) {
        if (jrLi.parentNode.children[i].id === `bname${jrId}`) {
            jrLi.parentNode.children[i].children[0].style.backgroundColor = "#acceff"
        } else {
            jrLi.parentNode.children[i].children[0].style.backgroundColor = ""
        }
    }

    let companyName;
    let jrTelephone;
    let companyAddress;

    $.ajax({
        headers: {
            "id": localStorage.getItem("id"),
            "token": localStorage.getItem("token")
        },
        url: `/dev/RecruiterLogin/findByJrId/${jrId}`,
        type: "POST",
        async: false,
        success: function (result) {
            if (result.code === 200) {
                console.log(result)
                companyName = result.data.companyName == null ? "未知" : result.data.companyName
                jrTelephone = result.data.jrTelephone == null ? "未知" : result.data.jrTelephone
                companyAddress = result.data.companyAddress == null ? "未知" : result.data.companyAddress
            }
        }
    })


    let jsId = localStorage.getItem("id")


    let chatMessage = "";

    $.ajax({
        headers: {
            "id": localStorage.getItem("id"),
            "token": localStorage.getItem("token")
        },
        type: 'POST',
        url: `/dev/cANDm/chatMessageJS/${jrId}/${jsId}`,
        async: false,
        success: function (result) {
            console.log("==聊天记录==")
            console.log(result)
            if (result.code === 200) {
                if (result.data !== null) {
                    $.ajax({
                        headers: {
                            "id": localStorage.getItem("id"),
                            "token": localStorage.getItem("token")
                        },
                        url: `/dev/cANDm/JrAndJs/${jrId}/${jsId}`,
                        type: "POST",
                        async: false,
                        success: function (result) {
                            jsAvatar = result.data.jsAvatar;
                            jrAvatar = result.data.jrAvatar;
                        }
                    })
                }

                let data = result.data;

                for (let i = 0; i < data.length; i++) {
                    let photo = null
                    let msg = null
                    if (data[i].message.includes('/assets/img/')){
                        if (data[i].message.includes("❄")){

                            msg = data[i].message.split("❄")[0]
                            photo = data[i].message.split("❄")[1]
                        } else {
                            msg = data[i].message
                        }
                    } else {
                        msg = data[i].message
                    }

                    console.log("======>>>")
                    console.log(msg)
                    console.log(photo)

                    if (data[i].sign === 0) {
                        chatMessage += `<li class="item-myself">
                      <div class="message-text">
                        <!--存放消息div-->
                        <!-- <div class="text" > -->
                        <img src="${jsAvatar}"
                             class="message-img"
                             style="width: 46px;height: 46px;border-radius: 100%;float:right;">
                        <div class="text">
<!--                          <i class="status status-read"></i>-->
                          <div>
                            <p>
                              <!--发送消息的-->
                              <a href="${photo}" style="display: ${photo===null?'none':'block'}" target="_blank">
                                <img src="${photo}" style="display: ${photo===null?'none':'block'};height: 70px">
                              </a>
                              <span  id="chat-message" style="display: ${msg===null?'none':'block'}" >${msg}</span>
                            </p>
                          </div>
                        </div>
                      </div>
                      <!--清除浮动-->
                      <div style="clear: both;"></div>
                    </li>`
                    }
                    if (data[i].sign === 1) {
                        chatMessage += `<li class="item-myself">
                      <div class="message-text">
                        <!--存放消息div-->
                        <!-- <div class="text" > -->
                        <img src="${jrAvatar}"
                             class="message-img"
                             style="width: 46px;height: 46px;border-radius: 100%;float:left;">
                        <div class="text" style="float: none;background-color: white;border: 1px solid #0c0101;margin-left: 3px;border-radius: 8px;border-top-left-radius: 0">
<!--                          <i class="status status-read"></i>-->
                          <div>
                            <p>
                              <!--发送消息的-->
                              <a href="${photo}" style="display: ${photo===null?'none':'block'}" target="_blank">
                                <img src="${photo}" style="display: ${photo===null?'none':'block'};height: 70px">
                              </a>
                              
                              <span  id="chat-message" style="display: ${msg===null?'none':'block'}">${msg}</span>
                            </p>
                          </div>
                        </div>
                      </div>
                      <!--清除浮动-->
                      <div style="clear: both;"></div>
                    </li>`
                    }
                }
            }
        }
    })


    console.log(jrId)

    let messageCenter = document.querySelector(".message-center")
    messageCenter.innerHTML = `<div class="top-info">
              <div class="user-info">
                <p class="base-info">
                  <span class="name">${companyName}</span>
<!--                  <span class="base-title">人才经纪人</span>-->
                  <img style="display: none" src="https://img.bosszhipin.com/static/file/2022/fdszc4v9eo1672210548439.png"
                       width="53" height="20" class="chat-online-stats">
                </p>
              </div>
              <div class="message-position-content">
                <!--预留出来-->
                <div class=""></div>
                <div class="message-main">
                  <a href="" class="position-content">
<!--                    <span class="message-name salary">公司名:${companyName}</span>-->
                    <span class="salary">公司电话:${jrTelephone}</span>
                    <span class="salary">公司地址:${companyAddress}</span>

                  </a>
                  <div class="message-tips" >温馨提示:友好交流，共建美好社会</div>
                </div>
              </div>

            </div>


            <!--空白区域-->
            <div class="message-import">
              <div class="message-record">
                <div class="chat-message" id="chat-in">
                  <ul class="im-list">
                    ${chatMessage}
                  </ul>
                </div>
                <!--ul-->

              </div>
            </div>


            <!--分界线-->
            <div class="message-controls">
              <div class="chat-editor">
                <div class="chat-controls">

<!--                <div class="layui-upload-drag" style="display: block;" id="ID-upload-demo-drag">-->
<!--                  <i class="layui-icon layui-icon-upload"></i> -->
<!--                  <div>点击上传，或将文件拖拽到此处</div>-->
<!--                  <div class="layui-hide" id="ID-upload-demo-preview">-->
<!--                    <hr> <img src="" alt="上传成功后渲染" style="max-width: 100%">-->
<!--                  </div>-->
<!--                </div>-->
                    <div aria-label="发送图片" class="icon btn-sendimg" id="ID-upload-demo-form-files">
        
                </div>

                


                <div class="chat-op">
                    <img src="#" style="display: none;height: 50px;" id="Mpicture">
                    <input style="width: 100%" class="tip" style="color: black" id="message-input" placeholder="按Enter键发送,按Ctrl+Enter键换行">
                    <button type="button" style="position: absolute;height: 26px;width: 64px;top: 150px;right: 50px" id="send-button" class="btn-send">发送</button>
                </div>


                <!----->




              </div>
            </div>`



    document.getElementById("chat-in").scrollTop = document.getElementById("chat-in").querySelector(".im-list").offsetHeight;

    layui.use(function(){
        var upload = layui.upload;
        var layer = layui.layer
        // 渲染
        upload.render({
            elem: '#ID-upload-demo-form-files',
            url: `/dev/picture/getpicture/${localStorage.getItem("id")}`, // 此处配置你自己的上传接口即可
            headers: {
                "id": localStorage.getItem("id"),
                "token": localStorage.getItem("token")
            },
            done: function(res){
                // layer.msg('上传成功');
                console.log(res)
                document.getElementById("Mpicture").style.display="block"
                // document.getElementById("message-input").style.display="none"
                document.getElementById("Mpicture").src = res;
            }
        });
    });


    wsS(jsId, jrId)

}


function wsS(jsId, jrId) {
    $.ajax({
        headers: {
            "id": localStorage.getItem("id"),
            "token": localStorage.getItem("token")
        },
        url: `/dev/cANDm/JrAndJs/${jrId}/${jsId}`,
        type: "POST",
        success: function (result) {
            jsAvatar = result.data.jsAvatar;
            jrAvatar = result.data.jrAvatar;
        }
    })


    let postId = params.get("postId")
    let ws;
    //检测浏览器是否支持webSocket
    if ("WebSocket" in window) {
        // $("#im-list").html("您的浏览器支持webSocket!");
        //模拟产生clientID
        let clientID = jsId;

        //创建 WebSocket 对象,注意请求路径！！！！
        //部署的时候,需要修改成真实的ip地址
        ws = new WebSocket("ws://127.0.0.1:8088/dev/tt/" + clientID);

        //与服务端建立连接时触发
        ws.onopen = function () {
            // $("#im-list").append("<p>与服务端建立连接建立成功！您的客户端ID="+clientID+"</p>");
            const messageInput = document.getElementById("message-input");
            const sendButton = document.getElementById("send-button");
            const chatMessages = document.getElementById("chat-message");
            let imList = document.querySelectorAll(".im-list")[0]

            sendButton.addEventListener("click", () => {
                // 获取消息文本
                let messageText = messageInput.value.trim();
                if (document.getElementById("Mpicture").style.display!=="none"){
                    console.log(document.getElementById("Mpicture").src)
                    messageText += '❄'+document.getElementById("Mpicture").src
                    document.getElementById("Mpicture").style.display="none"
                }

                if (messageText !== "") {
                    // 清空消息输入框
                    messageInput.value = ""

                    console.log(postId)
                    if (postId == null) {
                        ws.send(jrId + "|" + messageText + "|js")
                    } else {
                        ws.send(jrId + "|" + messageText + "|js|" + postId)
                    }

                    // ws.send(messageText);
                }
            });

            // 监听输入框的回车键事件
            messageInput.addEventListener("keydown", (event) => {
                if (event.key === "Enter") {
                    event.preventDefault(); // 防止回车键换行
                    sendButton.click(); // 模拟点击发送按钮
                }
            });
            //模拟发送数据到服务器

        }

        //接收到服务端消息时触发
        ws.onmessage = function (evt) {

            let received_msg = evt.data;
            let fsId = received_msg.split("|")[0]
            let msg = received_msg.split("|")[1]
            let imList = document.querySelectorAll(".im-list")[0]

            // $("#content").append("<p>接收到服务端消息:"+received_msg+"</p>");
            let msgr = null
            let photo = null
            if (msg.includes('/assets/img/')){
                if (msg.includes("❄")){

                    msgr = msg.split("❄")[0]
                    photo = msg.split("❄")[1]
                } else {
                    msgr = msg
                }
            } else {
                msgr = msg
            }

            if (fsId === jsId) {

                let str = `<li class="item-myself">
                      <div class="message-text">
                        <!--存放消息div-->
                        <!-- <div class="text" > -->
                        <img src="${jsAvatar}"
                             class="message-img"
                             style="width: 46px;height: 46px;border-radius: 100%;float:right;">
                        <div class="text">
<!--                          <i class="status status-read"></i>-->
                          <div>
                            <p>
                              <!--发送消息的-->
                              <a href="${photo}" style="display: ${photo===null?'none':'block'};"  target="_blank">
                                    <img src="${photo}" style="display: ${photo===null?'none':'block'};height: 70px">
                              </a>
                              <span id="chat-message" style="display: ${msgr===null?'none':'block'}">${msgr}</span>
                            </p>
                          </div>
                        </div>
                      </div>
                      <!--清除浮动-->
                      <div style="clear: both;"></div>
                    </li>`
                imList.innerHTML += str
                console.log("图片==》1")
                console.log(msg.includes('/assets/img/'))
                if (msg.includes('/assets/img/')){

                    document.getElementById("ppp").style.display="block";
                    document.getElementById("chat-message").style.display="none"
                }
                document.getElementById("chat-in").scrollTop = document.getElementById("chat-in").querySelector(".im-list").offsetHeight;
            } else {
                let str = `<li class="item-myself">
                      <div class="message-text">
                        <!--存放消息div-->
                        <!-- <div class="text" > -->
                        <img src="${jrAvatar}"
                             class="message-img"
                             style="width: 46px;height: 46px;border-radius: 100%;float:left;">
                        <div class="text" style="float: none;background-color: white;border: 1px solid #0c0101;margin-left: 3px;border-radius: 8px;border-top-left-radius: 0">
<!--                          <i class="status status-read"></i>-->
                          <div>
                            <p>
                              <!--发送消息的-->
                                <a href="${photo}" style="display: ${photo===null?'none':'block'};"  target="_blank">
                                    <img src="${photo}" style="display: ${photo===null?'none':'block'};height: 70px">
                                </a>
                              <span  id="chat-message" style="display: ${msgr===null?'none':'block'}">${msgr}</span>
                            </p>
                          </div>
                        </div>
                      </div>
                      <!--清除浮动-->
                      <div style="clear: both;"></div>
                    </li>`
                imList.innerHTML += str
                console.log("图片==》2")
                console.log(msg.includes('/assets/img/'))
                if (msg.includes('/assets/img/')){

                    document.getElementById("ppp").style.display="block";
                    document.getElementById("chat-message").style.display="none"
                }
                document.getElementById("chat-in").scrollTop = document.getElementById("chat-in").querySelector(".im-list").offsetHeight;
            }

        };

        //服务端关闭连接时触发
        ws.onclose = function () {
            console.error("连接已经关闭.....")
        };
    } else {
        $("#im-list").html("您的浏览器不支持webSocket！");
    }
}


$(function () {
    console.log("=加载初始化=")
    let jsId = localStorage.getItem("id")
    $.ajax({
        headers: {
            "id": localStorage.getItem("id"),
            "token": localStorage.getItem("token")
        },
        url: `/dev/cANDm/message/${jsId}`,
        type: "POST",
        async: false,
        success: function (result) {
            console.log("===result===")
            console.log(result)
            let data = result.data;
            let chatMessage = document.getElementById("chatMessage");
            let src = ""
            for (let i = 0; i < data.length; i++) {
                src += `<li role="listitem" onclick="chitchat(${data[i].jrId})" id="bname${data[i].jrId}">
                    <div class="first-content">
                        <div class="figure">
                            <img src="/dev/assets/img/gg.jpg" class="message-img">
                        </div>
                        <div class="text">
                            <div>
                                <!--时间-->
                                <!--                              <span class="time">11.56</span>-->
                            </div>
                            <div class="title-box">
                                                                <span class="name-box">
                                                                    <span class="name-text"
                                                                          id="jrName">${data[i].jrName}</span>
                                                                </span>
                            </div>
                            <div class="last-msg">
                                <span class="last-msg-text">最近消息:${data[i].lastChatTime}</span>
                                <div class="hr-operation">
                                    <img src="" class="icon-operate">
                                        <img src="" class="icon-operate">
                                </div>
                            </div>
                        </div>
                    </div>
                </li>`
            }
            chatMessage.innerHTML = src
        }
    })
})


$(function () {

    if (params != null) {
        var jrId = params.get('jrId');
        if (jrId != null) {
            let chatMessage = document.getElementById("chatMessage")
            $.ajax({
                headers: {
                    "id": localStorage.getItem("id"),
                    "token": localStorage.getItem("token")
                },
                url: `/dev/RecruiterLogin/findByJrId/${jrId}`,
                type: "POST",
                async: false,
                success: function (result) {
                    let data = result.data;
                    console.log("获取信息")
                    console.log(result)
                    let bol = true
                    for (let i = 0; i < chatMessage.children.length; i++) {
                        if (chatMessage.children[i].id === `bname${data.id}`) {
                            bol = false
                        }
                    }

                    if (bol) {
                        let newsrc = `<li role="listitem" onclick="chitchat(${data.id})" id="bname${data.id}">
                        <div class="first-content" >
                            <div class="figure">
                                <img src="/dev/assets/img/gg.jpg" class="message-img">
                            </div>
                            <div class="text">
                                <div>
                                    <!--时间-->
                                    <!--                              <span class="time">11.56</span>-->
                                </div>
                                <div class="title-box">
                                                                <span class="name-box">
                                                                    <span class="name-text">${data.companyName}</span>
                                                                    <!--|分节符-->
                                                                    <i class="vline"></i>
                                                                </span>
                                </div>
                                <div class="last-msg">
                                    <span class="last-msg-text">最新消息:${new Date()}</span>
                                    <div class="hr-operation">
                                        <img src="" class="icon-operate">
                                            <img src="" class="icon-operate">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </li>`
                        chatMessage.innerHTML += newsrc
                    }
                    chitchat(data.id)
                }
            })
        }
    }


})


let searchButton = document.getElementById("searchButton")
searchButton.onclick = function () {
    let searchInput = document.getElementById("searchInput").value
    let chatMessage = document.getElementById("chatMessage")
    if (searchInput !== "") {
        for (let i = 0; i < chatMessage.children.length; i++) {
            let src = chatMessage.children[i].children[0].children[1].children[1].children[0].children[0].innerText
            let Ssrc = new RegExp(searchInput)
            if (!Ssrc.test(src)) {
                chatMessage.children[i].style.display = "none"
            } else {
                chatMessage.children[i].style.display = ""
            }
        }
    } else {
        for (let i = 0; i < chatMessage.children.length; i++) {
            chatMessage.children[i].style.display = ""
        }
    }
}



